'use client';

import { useEffect, useState } from 'react';
import mixpanel from 'mixpanel-browser';
import { isHttpOrHttps } from '@/lib/tool';
import { useQuery } from '@tanstack/react-query';
import type { IUserBasicInfo } from '@/interfaces';
import { queryUserBasicInfo } from '@/services/api';
import useUser from '@/hooks/useUser';
import Script from 'next/script';
import type { TMetadata } from '@/types';
import { usePathname } from 'next/navigation';

export default function AnalysisWrapper({ metadata }: { metadata: TMetadata }) {
  const env = metadata.env;
  const pathname = usePathname();
  const [isLoadPlausible, setIsLoadPlausible] = useState(false);
  const [isLoadUmami, setIsLoadUmami] = useState(false);
  const userQuery = useUser(metadata);
  const queryUserBasicInfoQuery = useQuery(
    ['/users', userQuery.data?.user?.id, '/basic'],
    async (context) => {
      return (await queryUserBasicInfo({
        id: context.queryKey[1] as string,
      })) as IUserBasicInfo;
    },
    {
      enabled: !!(userQuery.data && userQuery.data.user),
    },
  );

  useEffect(() => {
    function handleMixpanel() {
      if (env.MIXPANEL !== 'true') {
        return;
      }

      mixpanel.init(env.MIXPANEL_PROJECT_TOKEN as string, {
        debug: env.MIXPANEL_DEBUG === 'true',
      });

      if (queryUserBasicInfoQuery.data) {
        const {
          id,
          alias,
          username,
          lastLoginTime,
          details,
          createdOn,
          updatedOn,
        } = queryUserBasicInfoQuery.data;
        const avatar =
          details.largeAvatarUrl ||
          details.mediumAvatarUrl ||
          details.smallAvatarUrl;
        const prop = {
          uid: id,
          alias: alias,
          username,
          lastLoginTime,
          createdOn,
          updatedOn,
          $name: alias,
        } as any;

        if (avatar) {
          prop.$avatar = isHttpOrHttps(avatar)
            ? avatar
            : env.APP_OSS_SERVER + avatar;
        }

        mixpanel.identify(id + '');
        mixpanel.people.set(prop);
      }

      mixpanel.track(pathname || location.pathname);
    }

    handleMixpanel();
  }, [
    env.MIXPANEL,
    env.MIXPANEL_DEBUG,
    env.MIXPANEL_PROJECT_TOKEN,
    env.APP_OSS_SERVER,
    queryUserBasicInfoQuery.data,
    pathname,
  ]);
  useEffect(() => {
    function handlePlausible() {
      if (env.PLAUSIBLE !== 'true') {
        return;
      }

      let p: string;
      let prop = {
        href: location.href,
        protocol: location.protocol,
        host: location.host,
        hostname: location.hostname,
        port: location.port,
        pathname: location.pathname,
        search: location.search,
        hash: location.hash,
        origin: location.origin,
      };

      if (queryUserBasicInfoQuery.data) {
        const {
          id,
          alias,
          username,
          lastLoginTime,
          details,
          createdOn,
          updatedOn,
        } = queryUserBasicInfoQuery.data;
        const avatar =
          details.largeAvatarUrl ||
          details.mediumAvatarUrl ||
          details.smallAvatarUrl;
        const _prop = {
          id,
          alias,
          username,
          lastLoginTime,
          createdOn,
          updatedOn,
          avatar: '',
        } as any;

        if (avatar) {
          _prop.avatar = isHttpOrHttps(avatar)
            ? avatar
            : env.APP_OSS_SERVER + avatar;
        }

        prop = { ...prop, ..._prop };
      }

      p = JSON.stringify(prop);

      // @ts-ignore
      plausible(pathname || location.pathname, { props: p });

      // @ts-ignore
      plausible('pageview', {
        u: `${location.origin}/${pathname || location.pathname}`,
        props: p,
      });
    }

    // @ts-ignore
    if (isLoadPlausible && window.plausible) {
      handlePlausible();
    }
  }, [
    env.APP_OSS_SERVER,
    isLoadPlausible,
    queryUserBasicInfoQuery.data,
    pathname,
    env.PLAUSIBLE,
  ]);

  function onLoadPlausible() {
    setIsLoadPlausible(true);
  }

  function onLoadUmami() {
    setIsLoadUmami(true);
  }

  function onLoadPlausibleLocal() {
    setIsLoadPlausible(true);
    if (typeof localStorage !== 'undefined') {
      localStorage.setItem(
        'plausible_ignore',
        env.PLAUSIBLE_TRACK_LOCAL_HOST === 'true' ? 'false' : 'true',
      );
    }
  }

  return (
    <>
      {env.PLAUSIBLE === 'true' && (
        <>
          <Script
            defer
            data-domain={env.PLAUSIBLE_DATA_DOMAIN}
            data-api={`${env.PLAUSIBLE_DATA_API_DOMAIN}/api/event`}
            src="/lib/plausible/script.min.js"
            onLoad={onLoadPlausible}
          />
          <Script
            defer
            data-domain={env.PLAUSIBLE_DATA_DOMAIN}
            data-api={`${env.PLAUSIBLE_DATA_API_DOMAIN}/api/event`}
            src="/lib/plausible/script.outbound-links.file-downloads.min.js"
          />
          <Script
            defer
            data-domain={env.PLAUSIBLE_DATA_DOMAIN}
            data-api={`${env.PLAUSIBLE_DATA_API_DOMAIN}/api/event`}
            src="/lib/plausible/script.manual.min.js"
          />

          {env.PLAUSIBLE_TRACK_LOCAL_HOST === 'true' && (
            <Script
              defer
              data-domain={env.PLAUSIBLE_DATA_DOMAIN}
              data-api={`${env.PLAUSIBLE_DATA_API_DOMAIN}/api/event`}
              src="/lib/plausible/script.local.min.js"
              onLoad={onLoadPlausibleLocal}
            />
          )}

          {isLoadPlausible && (
            <Script
              id="plausible-analytics"
              dangerouslySetInnerHTML={{
                __html:
                  'window.plausible = window.plausible || function() { (window.plausible.q = window.plausible.q || []).push(arguments) }',
              }}
            />
          )}
        </>
      )}

      {env.UMAMI === 'true' && (
        <Script
          defer
          src={env.UMAMI_SRC || '/lib/umami/script.min.js'}
          data-website-id={env.UMAMI_WEBSITE_ID}
          data-cache={env.UMAMI_DATA_CACHE}
          data-host-url={env.UMAMI_DATA_HOST_URL}
          onLoad={onLoadUmami}
        />
      )}
    </>
  );
}
